package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.atguigu.gulimall.product.vo.BaseAttrs;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@SuppressWarnings("all")
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Resource
    public AttrAttrgroupRelationDao relationDao;

    @Resource
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryService categoryService;

//    @Autowired
//    private ProductConstant productConstant;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        return new PageUtils(page);
    }

    @SuppressWarnings("all")
    /**
     * 根据分组id找到关联的所有属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList
                (new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrgroupId));
        //因为是一个集合，也就是entities中就是一个分组对应的关联属性关系苏哦一每一个分组都是一个list，获取属性的id用流
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //根据attrIds查找所有的属性信息
        //Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        //如果attrIds为空就直接返回一个null值出去
        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }
        List<AttrEntity> attrEntityList = this.baseMapper.selectBatchIds(attrIds);
        return attrEntityList;
    }

    /**
     * 获取当前分组没有被关联的所有属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @SuppressWarnings("all")
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //获取当前分类的id
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1）、当前分类下的其它分组
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        //获取到所有的attrGroupId
        List<Long> collect = groupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2.2）、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList
                (new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        //已经关联的所有属性的id
        List<Long> attrIds = groupId.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.3）、从当前分类的所有属性移除这些属性 [因这些分组已经存在被选了 就不用再显示了]
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }
        //判断是否有参数进行模糊查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public void deleteRelation(List<AttrAttrgroupRelationEntity> vos) {
        //relationDao.delete(new QueryWrapper<>().eq("attr_id",1L).eq("attr_group_id",1L));
        //DELETE FROM `pms_attr_attrgroup_relation` WHERE
        // (attr_id = 1 AND attr_group_id =1) OR (attr_id = 1 AND attr_group_id =1);如果还有继续删除

//        List<AttrAttrgroupRelationEntity> entities = vos.stream().map((item) -> {
//            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
//            BeanUtils.copyProperties(item, relationEntity);
//            return relationEntity;
//        }).collect(Collectors.toList());
//        relationDao.deleteBatchRelation(entities);
        relationDao.deleteBatchRelation(vos);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        //保存基本数据
        AttrEntity attrEntity = new AttrEntity();
//        attrEntity.setAttrName(attrVo.getAttrName());
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);

//        if (attrVo.getAttrType() == 1) {
//            //如果是销售属性，不需要处理分组信息
//        }
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrSort(0);
            relationDao.insert(relationEntity);
//        attrAttrgroupRelationService.save(relationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        // 表明查询的是 属性类型[0-销售属性，1-基本属性，2-既是销售属性又是基本属性]
        // 传入的attrType是"base"或其他，但是数据库存的是 "0"销售 / "1"基本
        // 属性都在pms_attr表中混合着
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(type) ? 1 : 0);
        if (catelogId != 0) {//如果不是0，就根据catelogID查，如果是0，就是查询全部
            wrapper.eq("catelog_id", catelogId);
        }
        if (!StringUtils.isEmpty((String) params.get("key"))) {//如果搜索条件不为空
            wrapper.and((queryWrapper) -> {
                queryWrapper.eq("attr_id", (String) params.get("key")).or()
                        .like("attr_name", (String) params.get("key"));
            });
//            wrapper.and(new Consumer<QueryWrapper<AttrEntity>>() {
//                @Override
//                public void accept(QueryWrapper<AttrEntity> queryWrapper) {
//                    queryWrapper.eq("attr_id", (String) params.get("key")).or()
//                        .like("attr_name", (String) params.get("key"));
//                }
//            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();//得到所有的记录
        //========[AttrEntity(attrId=1, attrName=入网参数, searchType=1, icon=xxx,
        // valueSelect=4G;5G, attrType=1, enable=1, catelogId=225, showDesc=1)
        System.out.println("========" + records);
        //要返回的RespVo的list
        List<AttrRespVo> attr_id = records.stream().map((attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);//先讲attrEntity的基本属性设置到attrRespVo对象中
            // 1.设置分类和分组的名字  先获取中间表对象  给attrRespVo 封装分组名字
            if ("base".equalsIgnoreCase(type)) { // 如果是规格参数才查询，或者说销售属性没有属性分组，只有分类
                // 根据属性id查询关联表，得到其属性分组
                AttrAttrgroupRelationEntity entity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (entity != null && entity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(entity);
                    // 设置属性分组的名字
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        })).collect(Collectors.toList());
        pageUtils.setList(attr_id);
        return pageUtils;
    }

    //更新回显数据
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        //封装基本数据
        BeanUtils.copyProperties(attrEntity, attrRespVo);

//        attrRespVo.setValueType(attrEntity.getValueType());

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //设置分组信息
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));
            //下面两处不要忘记判断，否则会报空指针异常
            Long attrGroupId = null;
            if (relationEntity != null) {
                attrGroupId = relationEntity.getAttrGroupId();
            }
            if (attrGroupId != null) {
                attrRespVo.setAttrGroupId(attrGroupId);
            }
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
            if (attrGroupEntity != null) {
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }


        //设置分类信息
        Long catelogId = attrRespVo.getCatelogId();//225
        //根据catelogId查询catelogPath【2，34，225】这种形式显示在修改页面
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        //封装catelogName,分类名称
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }


    @Transactional  //两个都更新成功才算成功，因此要加事务进行控制
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        //先修改基本属性,基本数据都来源于页面attrVo
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //判断groupname是否有值，如果有就修改，如果没有就新增
            //此处可以使用mybatisplus中的saveorupdate方法
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrVo.getAttrId()));
            if (count > 0) {
                //修改关联的所在组信息
                //根据attr_id从关联表中找到group_id，然后修改关联表
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                relationEntity.setAttrId(attrVo.getAttrId());
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrVo.getAttrId()));
            } else {
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                relationEntity.setAttrId(attrVo.getAttrId());
                relationDao.insert(relationEntity);
            }
        }

    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        //sql：select attr_id from psm_attr where attr_id in(?) and search_type = 1
        return baseMapper.selectSearchAttrs(attrIds);
    }


}